//
//  XLOutchViewController.swift
//  WeiBo
//
//  Created by macbook on 16/10/17.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit
import SVProgressHUD

class XLOutchViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view = webView
        self.view.backgroundColor = UIColor.whiteColor();
        setNavItem()
        
        
        
    }
    
    //设置导航条
    func setNavItem()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(XLOutchViewController.canncleClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(XLOutchViewController.sitFillText))
    }
    
    private lazy var webView:UIWebView = {
    
        let web = UIWebView()
        web.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        let request = NSURLRequest(URL: url!)
        web.loadRequest(request)
        return web
    }()
    
    
    
    //取消实现
    @objc private func canncleClick()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //填充实现
    @objc private func sitFillText()
    {
        let jsSting = "document.getElementById('userId').value='13022285567',document.getElementById('passwd').value='buzhiduicuo'"
        
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsSting)
    }


}

extension XLOutchViewController:UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        
    }
    
    
    
//    若果返回true,代表继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //把url转换成字符串
        let urlString = request.URL?.absoluteString
//        urlString?.hasPrefix(<#T##prefix: String##String#>)判断url是否有值
 
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            
            let quest = request.URL?.query
            
            if let q = quest {
                
                //字符串截取,拿到code ,拿到code就能拿到accessToke
                let code = q.substringFromIndex("code=".endIndex)
                
                print(code)
                loadUserAccess(code)
            }
            
        }
        
        return true
    }
}

extension XLOutchViewController
{
    func loadUserAccess(code:String)
    {
        XLNetworkTools.shardTools.oauthLoadUserAccout(code, success: { (reponse) in
            //判断请求回来的是否有值,并且是否可以转换成字典
            guard let res = reponse as? [String:AnyObject] else
            {
                print("这不是一个字典")
                return;
            }
            
            let userAccount = XLUserAccout(dict: res)
            
//            print("返回=\(userAccount)")
            self.loadUserInfo(userAccount)
            }) { (error) in
                
                print("%@",error)
        }
    }
    
    func loadUserInfo(userAccou:XLUserAccout)
    {
        XLNetworkTools.shardTools.loadUserInfo(userAccou, succeess: { (reponse) in
            guard let re = reponse as? [String:AnyObject] else
            {
                return;
            }
            
            
            userAccou.avatar_large = re["avatar_large"] as? String
            userAccou.screen_name = re["screen_name"] as? String
            
            //归档保存数据
            XLUserAccountTools.shardTools.saveUserAccount(userAccou)
            
            self.dismissViewControllerAnimated(false, completion: { 
                
                //关闭指示器
                SVProgressHUD.dismiss()
                
                NSNotificationCenter.defaultCenter().postNotificationName(SwiftRootViewController, object: nil)
                
                
            })
            
            print("拿到的数据\(userAccou)")
            
            }) { (error) in
                
                print("请求个人数据出错")
        }
    }
    
}










